import md5 from 'js-md5'
// import { uploadVideoChunkAxios, mergeFileAxios, uploadCheckAxios } from '@/api/upload'
import {
    breakpointUploadFile,
    addFile,
    checkFile
} from '@/api/index'

export const uploadByPieces = ({
    file,
    pieceSize = 2,
    progress,
    success,
    error
}) => {
    let time = new Date().getTime();
    let fileName=time+'_'+file.name
    // file.name=fileName
    // if (!file || !file.length) return
    // 上传过程中用到的变量
    let fileMD5 = '' // 总文件列表
    const chunkSize = pieceSize * 1024 * 1024 // 5MB一片
    const chunkCount = Math.ceil(file.size / chunkSize) // 总片数
    let per=chunkCount/100
    let percentage=0
    // this.percentage = Number((arr.length * per).toFixed(2));
    // 获取md5
    const readFileMD5 = () => {
        // 读取视频文件的md5
        console.log("获取文件的MD5值")
        let fileRederInstance = new FileReader()
        fileRederInstance.readAsBinaryString(file)
        fileRederInstance.addEventListener('load', async e => {
            console.log(e.target, "hhhhhh")
            let fileBolb = e.target.result
            fileMD5 = md5(fileBolb)
            let checkFileResult = await checkFile({
                "md5": fileMD5,
                fileName: fileName,
            })
            if (checkFileResult.data.msg !='上传失败') {
                readChunkMD5()
            } else {
                error && error('调用接口check-file返回错误信息：' + checkFileResult.data.msg)
            }
            // .then(res => {
            //     if(res.data.msg=='SUCCESS'){
            //         readChunkMD5()
            //     }
            // }).catch((e) => {
            //     error&&error('接口check-file'+res.data.msg)
            //     console.log("文件合并错误")
            //     console.log(e)
            // })

        })
    }
    const getChunkInfo = (file, currentChunk, chunkSize) => {
        let start = currentChunk * chunkSize
        let end = Math.min(file.size, start + chunkSize)
        let chunk = file.slice(start, end)
        return {
            start,
            end,
            chunk
        }
    }
    // 针对每个文件进行chunk处理
    const readChunkMD5 = () => {
        // 针对单个文件进行chunk上传
        for (var i = 0; i < chunkCount; i++) {
            const {
                chunk
            } = getChunkInfo(file, i, chunkSize)
            console.log("总片数" + chunkCount)
            console.log("分片后的数据---测试：" + i)
            console.log(chunk)
            uploadChunk({
                chunk,
                currentChunk: i,
                chunkCount
            })
        }
    }
    const uploadChunk = async (chunkInfo) => {
        // progressFun()
        let fetchForm = new FormData()
        fetchForm.append('chunk', chunkInfo.currentChunk)
        fetchForm.append('chunkSize', chunkSize)
        fetchForm.append('chunks', chunkInfo.chunkCount)
        fetchForm.append('file', chunkInfo.chunk)
        fetchForm.append('md5', fileMD5)
        fetchForm.append('name', fileName)
        let result1 = await breakpointUploadFile(fetchForm)
        if (result1.data.msg == 'SUCCESS') {
            percentage=Number((chunkInfo.currentChunk * per).toFixed(2));
            if (chunkInfo.currentChunk >= chunkInfo.chunkCount - 1) {
                let result2 = await addFile({
                    "md5": fileMD5,
                    "fileName":fileName
                })
                if (result2.data.msg == 'SUCCESS') {
                    success && success(result2.data)
                } else {
                    error && error('调用接口files/add返回错误信息：' + result2.data.msg)
                }
            }else{
                success && success(percentage) 
            }
        } else {
            error && error('调用接口breakpoint-upload返回错误信息：' + result1.data.msg)
        }
        // breakpointUploadFile(fetchForm).then(res => {
        //     console.log("分片上传返回信息：")
        //     console.log(res.data)
        //     if (res.data.msg == 'SUCCESS') {
        //         success && success(res)
        //         if (chunkInfo.currentChunk < chunkInfo.chunkCount - 1) {
        //             console.log("分片上传成功")
        //         } else {
        //             console.log(chunkInfo.currentChunk, chunkInfo.chunkCount - 1, "kgdf")
        //             // 当总数大于等于分片个数的时候
        //             if (chunkInfo.currentChunk >= chunkInfo.chunkCount - 1) {
        //                 console.log("文件开始------合并成功")
        //                 addFile({
        //                     "md5": fileMD5,
        //                     "fileName": file.name
        //                 }).then(res => {
        //                     if (res.data.msg == 'SUCCESS') {
        //                         //  success && success(res)
        //                         // console.log("文件合并成功")
        //                         //  console.log(res.data.data.url)
        //                     } else {
        //                         console.log(res.data.msg)
        //                     }
        //                 }).catch((e) => {
        //                     console.log("文件合并错误")
        //                     console.log(e)
        //                 })
        //             }
        //         }
        //     } else {
        //         console.log(res.data.msg)
        //     }
        // }).catch((e) => {
        //     error && error(e)
        // })
    }
    readFileMD5() // 开始执行代码
}